//
//  FMContactController.m
//  flutter_device_info_plugin
//
//  Created by 小琦 on 2025/3/2.
//

#import "FMContactController.h"
#import <ContactsUI/ContactsUI.h>

@interface FMContactController ()<CNContactPickerDelegate>

@end

@implementation FMContactController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self initContactController];
}

- (void)initContactController {
    CNContactPickerViewController *picker = [[CNContactPickerViewController alloc] init];
    picker.delegate = self;
    
    [self.view addSubview:picker.view];
    [self addChildViewController:picker];
}

#pragma mark - CNContactPickerDelegate

- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
    NSString *givenName = contact.givenName;
    NSString *familyName = contact.familyName;
    NSString *fullName = [NSString stringWithFormat:@"%@ %@", givenName,familyName];
    
    NSString *phoneNumber = nil;
    if (contact.phoneNumbers.count > 0) {
        CNPhoneNumber *phone = contact.phoneNumbers.firstObject.value;
        phoneNumber = phone.stringValue;
    }
    
    if (self.contactHandle) {
        self.contactHandle(fullName, phoneNumber);
    }
}

@end
